import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { TreetableComponent, TreeTableNode } from '@iux/live';
import { TreetableService } from '../tree-table.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-drag',
  templateUrl: './drag.component.html',
  styles: [
    `
      .app-custom-placeholder {
        background: #ccc;
        border: dotted 3px #999;
        height: 40px;
        transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
      }
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DragComponent implements OnInit {
  data: TreeTableNode[];

  @ViewChild(TreetableComponent, { static: true }) lvTable: TreetableComponent;

  constructor(private treeTableService: TreetableService, private cdr: ChangeDetectorRef) { }

  ngOnInit() {
    this.initAsyncData();
  }

  initAsyncData() {
    this.treeTableService.getUsers2().subscribe((res: TreeTableNode[]) => {
      this.data = res;
      this.cdr.markForCheck();
    });
  }

  // TODO: 拖拽功能问题，已单独提单记录
  drop(event: CdkDragDrop<string[]>): void {
    const data = this.lvTable.getParentData(event.item.data).children;
    moveItemInArray(data, event.previousIndex, event.currentIndex);
  }

  expandedChange(expanded: boolean, item: TreeTableNode): void {
    this.data = [...this.data];
    // data地址发生变更
    if (expanded) {
      for (const data of this.lvTable.renderData) {
        data.expanded = false;
      }

      item.expanded = true;
    }
  }
}
